package com.zygh.interactiveplatform.common.aop;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.URLUtil;
import com.alibaba.druid.sql.visitor.functions.Trim;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zygh.interactiveplatform.common.anno.PcLog;
import com.zygh.interactiveplatform.module.entity.Operation;
import com.zygh.interactiveplatform.module.mapper.OperationMapper;
import com.zygh.interactiveplatform.module.service.TokenService;
import com.zygh.interactiveplatform.util.JwtTokenUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.time.Instant;
import java.util.Arrays;
import java.util.Map;


/**
 * pc端操作日志，切面处理类
 */
@Aspect
@Component
public class SysPCLogAspect {
    private static final Logger loger = LoggerFactory.getLogger(SysPCLogAspect.class);
    private Operation sysLog = new Operation();

    @Resource
    private OperationMapper operationMapper;
    @Resource
    private TokenService tokenService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    /**
     * 定义切点 @Pointcut
     * 在注解的位置切入代码
     */
    @Pointcut("@annotation(com.zygh.interactiveplatform.common.anno.PcLog)")
    public void logPoinCut() {
    }


    @AfterThrowing(value = "logPoinCut()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Exception e) {
        handleLog(joinPoint, e);
    }

    protected void handleLog(final JoinPoint joinPoint, final Exception e) {
        try {

            // 开始时间
            long beginTime = Instant.now().toEpochMilli();
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String remoteIP = getRemoteIP(request);
            // 客户端ip
            //String ip = request.getRemoteAddr();
            // 操作人账号、姓名
            String token = tokenService.getTokenByHeader(request);

            if (token != null) {
                String username = jwtTokenUtil.getUserNameFromToken(token);
                sysLog.setUserName(username);
            }
            //浏览器唯一标识
            String sessionId = request.getSession().getId();
            //从切面织入点处通过反射机制获取织入点处的方法
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            //获取切入点所在的方法
            Method method = signature.getMethod();
            Class<PcLog> pc = PcLog.class;
            //获取操作--方法上的ViLog的值
            PcLog pcLog = method.getAnnotation(pc);
            if (pcLog != null) {
                //保存操作事件、日志类型//0：登录；1：查询；2：新增；3：修改；4：删除；5：登出；6：其他  不能为空
                sysLog.setLogType(pcLog.logType());
                //功能模块
                sysLog.setModule(pcLog.module());
                //请求内容
                sysLog.setContent(pcLog.content());
            }

            // 拦截的方法参数
            Object[] args = joinPoint.getArgs();
            String param = Arrays.toString(joinPoint.getArgs());
            JSONArray operateParamArray = new JSONArray();
            for (int i = 0; i < args.length; i++) {
                Object paramsObj = args[i];
                //通过该方法可查询对应的object属于什么类型：String type = paramsObj.getClass().getName();
                if (paramsObj instanceof String || paramsObj instanceof JSONObject) {
                    String str = (String) paramsObj;
                    System.out.println(str);
                    //将其转为jsonobject
                    JSONObject dataJson = JSONObject.parseObject(str);
                    if (dataJson == null || dataJson.isEmpty() || "null".equals(dataJson)) {
                        break;
                    } else {
                        operateParamArray.add(dataJson);
                    }
                } else if (paramsObj instanceof Map) {
                    //get请求，以map类型传参
                    //1.将object的map类型转为jsonobject类型
                    Map<String, Object> map = (Map<String, Object>) paramsObj;
                    JSONObject json = new JSONObject(map);
                    operateParamArray.add(json);
                }
            }


            // 请求标识uuid全局唯一   可以为空
            sysLog.setRequestId(IdUtil.simpleUUID());
            // session标识    不能为空
            sysLog.setSessionId(sessionId);
            // 终端标识ip  发起请求的终端ip地址，不能为空
            sysLog.setTerminalIp(remoteIP);
            // 源端口   可以为空
            sysLog.setSourcePort(8099);
            // 原始请求参数   可以为空
            sysLog.setParams(param);
            // 访问url   可以为空
            sysLog.setUrl(request.getRequestURL().toString());
            // uri     可以为空
            sysLog.setUri(URLUtil.getPath(request.getRequestURI()));
            // 响应内容类型html/json  不能为空  1.json 2.html
            sysLog.setResponseType("1");
            // 响应内容   不可以为空
            sysLog.setResponse("response");
            if (e == null) {
                // 访问结果成功失败  成功或失败，失败时要写失败原因  不能为空
                String str = HttpStatus.OK.toString();
                sysLog.setResult(str.replace(" ",""));
            }

            if (e != null) {
                // 失败日志   可以为空
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw, true);
                e.printStackTrace(pw);
                sysLog.setResult(pw.toString());
                // 失败原因   可以为空
                pw.flush();
                pw.close();
                sw.flush();
                sw.close();
            }
            // 服务的ip  可以为空
            sysLog.setDestIp(InetAddress.getLocalHost().getHostAddress());
            // 服务的端口  可以为空
            sysLog.setDestPort(request.getServerPort());
            // 日志记录时间,时间戳,格式如1519978042000   不能为空
            sysLog.setTime(DateUtil.now());
            // 请求耗时（ms）  可以为空
            long endTime = Instant.now().toEpochMilli();
            sysLog.setResponseTime((int) (endTime - beginTime));
            operationMapper.insert(sysLog);
        } catch (Exception exp) {
            loger.error("保存操作日志异常:{}", exp.getMessage());
            exp.printStackTrace();
        }

    }

    /**
     * 切面 配置通知
     *
     * @param joinPoint 切入点
     * @throws IOException IO异常
     */
    @AfterReturning("logPoinCut()")
    public void saveOperation(JoinPoint joinPoint) throws Exception {
        handleLog(joinPoint, null);
    }

    public static String getRemoteIP(HttpServletRequest request) {
        String ip = null;
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Forwarded-For");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip != null) {
            //对于通过多个代理的情况，最后IP为客户端真实IP,多个IP按照','分割
            int position = ip.indexOf(",");
            if (position > 0) {
                ip = ip.substring(0, position);
            }
        }
        return ip;
    }

}
